﻿//------------------------------------------------------------------------------
//Author: Christoph van der Fecht
//CodePlex: http://www.codeplex.com/site/users/view/ChristophvdF
//
//Copyright(c) Christoph van der Fecht
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using SerienNewsReader.Model;
using System.Xml.Linq;

namespace SerienNewsReaderMVVM
{
    public class Loader : IDisposable
    {
        private static readonly Loader instance = new Loader();
        /// <summary>
        /// Delegate for a completed download
        /// </summary>
        /// <param name="sender">Object that sends the event</param>
        /// <param name="e">Eventarguments</param>
        public delegate void DownloadCompletedDelegate(object sender, EventArguments.DownloadFinishedEventArgs e);

        /// <summary>
        /// Occures when a download is completed
        /// </summary>
        public event DownloadCompletedDelegate DownloadCompleted;

        /// <summary>
        /// Prevents the object from beeing created
        /// </summary>
        private Loader()
        { }

        /// <summary>
        /// Starts the download of all series and movies
        /// </summary>
        public void LoadSeries()
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri("http://serienjunkies.org/xml/feeds/episoden.xml", UriKind.Absolute));
        }

        /// <summary>
        /// Parses the loaded series and movies
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            ((WebClient)sender).DownloadStringCompleted -= client_DownloadStringCompleted;
            List<RSSFeed> series = new List<RSSFeed>();
            List<RSSFeed> movies = new List<RSSFeed>();

            if (e.Error == null && e.Cancelled == false)
            {            
                XElement xelement = XElement.Parse(e.Result);

                var items = xelement.Descendants(XName.Get("item"));

                foreach (var item in items)
                {
                    var title = item.Descendants(XName.Get("title")).SingleOrDefault();
                    string[] spliter = ((String)title.Value).Split(']');
                    String serienLanguage = spliter[0].Remove(0, 1);
                    String serienTitle = spliter[1].Replace('.', ' ').Trim();
                    var link = item.Descendants(XName.Get("link")).SingleOrDefault();
                    if (!link.Value.Contains("http://"))
                    {
                        link.Value = "https://" + link.Value;
                    }
                    RSSFeed feed = new RSSFeed(serienTitle, serienLanguage, new Uri(link.Value));

                    if (feed.Language.ToUpper().Equals("TV-FILM"))
                    {
                        movies.Add(feed);
                    }
                    else
                    {
                        series.Add(feed);
                    }
                }
            }

            movies.OrderBy(x => x.Title);
            series.OrderBy(x => x.Title);
            if (this.DownloadCompleted != null)
            {
                this.DownloadCompleted(this, new EventArguments.DownloadFinishedEventArgs(series, movies));
            }
        }

        public void Dispose()
        { }

        public static Loader Instance
        {
            get
            {
                return instance;
            }
        }
    }
}
